package pkg.action;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesServiceFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.stripes.action.After;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.ValidationErrors;
import pkg.dao.EntityDAO;
import pkg.dao.PagedList;
import pkg.entity.Grade;
import pkg.entity.Prefix;
import pkg.entity.Teacher;
import pkg.filter.GradeFilter;
import pkg.filter.PrefixFilter;
import pkg.filter.TeacherFilter;
import pkg.util.ImageUtil;

public class TeacherActionBean extends BaseActionBean {

    private PagedList<Teacher> teachers;
    private List<Teacher> teacherList;
    private List<Long> teacherIds;
    private Integer page;
    private String sort;
    private String dir;
    private String mode;
    private String filterText;
    private Teacher teacher;
    private List<Prefix> prefixes;
    private Map<Long, Prefix> prefixMap;
    private List<Grade> grades;
    private Map<Long, Grade> gradeMap;
    private FileBean picture;

    public TeacherActionBean() {
    }

    @DefaultHandler
    public Resolution view() {
        loadTeachers();
        loadMaps();
        return new ForwardResolution("/TeacherList.jsp");
    }

    public void loadTeachers() {
        EntityDAO sb;

        sb = new EntityDAO();
        //TODO
        TeacherFilter f = new TeacherFilter();
        filterText = (String) getSession().getAttribute("filterText");
        if (filterText != null) {
            f.setSimple(filterText);
        }
        teacherList = sb.findAllByFilter(f);
        teachers = new PagedList<Teacher>();
        teachers.setResults(sb.findAllByFilter(f));
        if (page == null) {
            page = 1;
        }
        teachers.setPageNumber(page);
    }

    public Resolution addNew() {
        return new RedirectResolution("/Teacher.action?create");
    }

    public Resolution deleteSelected() {
        EntityDAO sb = new EntityDAO();

        if (getTeacherIds() != null) {
            sb.delete(Teacher.class, teacherIds);
        }
        loadTeachers();
        setCache("teacherMap", null);
        setCache("teacherTime", new Date());
        RedirectResolution result;
        result = new RedirectResolution(this.getClass());
        result.addParameter("page", page);
        return result;
    }

    public Resolution preEdit() {
        EntityDAO sb;
        sb = new EntityDAO();
        teacher = sb.find(Teacher.class, teacher.getId());
        loadLookups();
        return new ForwardResolution("/TeacherEdit.jsp");
    }

    public Resolution save() throws IOException {
        EntityDAO sb = new EntityDAO();
        Teacher origItem = null;
        if (teacher.getId() != null) {
            origItem = sb.find(Teacher.class, teacher.getId());
        }

//            if (origItem == null) {
//                ValidationError error = new SimpleError("Item code is invalid.");
//                getContext().getValidationErrors().add("itemCode", error);
//                return getContext().getSourcePageResolution();
//            }

        if (picture != null) {
            byte[] newImage = ImageUtil.resizeImageStream(picture.getInputStream(), 100, 150);
            if (newImage == null) {
                addError(picture.getFileName() + " is not a valid image.");
                return getContext().getSourcePageResolution();
            }
            teacher.setPicBlob(newImage);
        }
        sb.update(teacher);
        setCache("teacherMap", null);
        setCache("teacherTime", new Date());
        RedirectResolution result;
        result = new RedirectResolution(this.getClass()); 
        result.addParameter("page", page);
        return result;
    }

    public Resolution image() {
        EntityDAO dao = new EntityDAO();

        teacher = dao.find(Teacher.class, teacher.getId());

        Image image = ImagesServiceFactory.makeImage(teacher.getPicBlob());
        return new StreamingResolution(ImageUtil.getContentType(image), new ByteArrayInputStream(image.getImageData()));
    }

    @After(stages = LifecycleStage.BindingAndValidation)
    public void loadRequestIfErrors() {
        ValidationErrors ve = getContext().getValidationErrors();
        if (ve.size() > 0 && teacher != null && teacher.getId() != null) {
            EntityDAO sb = new EntityDAO();
            teacher = sb.find(Teacher.class, teacher.getId());
        }
        loadLookups();
    }

    public Resolution create() {
        teacher = new Teacher();
        mode = "add";
        loadLookups();
        return new ForwardResolution("/TeacherEdit.jsp");
    }

    public Resolution applyFilter() {
        if (filterText != null) {
            getSession().setAttribute("filterText", filterText);
        } else {
            getSession().removeAttribute("filterText");
        }
        return new RedirectResolution(this.getClass());
    }

    public void loadLookups() {
        EntityDAO dao = new EntityDAO();
        PrefixFilter pf = new PrefixFilter();
        prefixes = dao.findAllByFilter(pf);
        GradeFilter gf = new GradeFilter();
        grades = dao.findAllByFilter(gf);
    }

    //<editor-fold defaultstate="collapsed" desc=" Setters/Getters ">
    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher category) {
        this.teacher = category;
    }

    public Teacher getItem() {
        return teacher;
    }

    public void setItem(Teacher item) {
        this.teacher = item;
    }

    public PagedList<Teacher> getTeachers() {
        return teachers;
    }

    public void setTeachers(PagedList<Teacher> items) {
        this.teachers = items;
    }

    public List<Teacher> getTeacherList() {
        return teacherList;
    }

    public void setTeacherList(List<Teacher> itemList) {
        this.teacherList = itemList;
    }

    public List<Long> getTeacherIds() {
        return teacherIds;
    }

    public void setTeacherIds(List<Long> TeacherIds) {
        this.teacherIds = TeacherIds;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public String getDir() {
        return dir;
    }

    public void setDir(String dir) {
        this.dir = dir;
    }

    public String getMode() {
        return mode;
    }

    public void setMode(String mode) {
        this.mode = mode;
    }

    public String getFilterText() {
        return filterText;
    }

    public void setFilterText(String filterText) {
        this.filterText = filterText;
    }

    public Map<Long, Grade> getGradeMap() {
        return gradeMap;
    }

    public void setGradeMap(Map<Long, Grade> gradeMap) {
        this.gradeMap = gradeMap;
    }

    public List<Grade> getGrades() {
        return grades;
    }

    public void setGrades(List<Grade> grades) {
        this.grades = grades;
    }

    public Map<Long, Prefix> getPrefixMap() {
        return prefixMap;
    }

    public void setPrefixMap(Map<Long, Prefix> prefixMap) {
        this.prefixMap = prefixMap;
    }

    public List<Prefix> getPrefixes() {
        return prefixes;
    }

    public void setPrefixes(List<Prefix> prefixes) {
        this.prefixes = prefixes;
    }

    private void loadMaps() {
        loadLookups();

        prefixMap = new HashMap<Long, Prefix>();
        for (Prefix p : prefixes) {
            prefixMap.put(p.getId(), p);
        }
        gradeMap = new HashMap<Long, Grade>();
        for (Grade g : grades) {
            gradeMap.put(g.getId(), g);
        }
    }

    public FileBean getPicture() {
        return picture;
    }

    public void setPicture(FileBean picture) {
        this.picture = picture;
    }
    //</editor-fold>
}
